package com.tao.dao.user.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;

import com.tao.dao.SupeDao;
import com.tao.dao.user.UserDao;
import com.tao.domain.User;

@Repository
public class UserDaoImpl extends SupeDao implements UserDao {

	@SuppressWarnings("unchecked")
	@Override
	public List<User> findAll(User t) {
		Session session = (Session) sessionFactory.openSession();

		String hql = "from User  where  1=1 ";
		if (null != t && !t.equals("")) {
			if (null != t.getUin() && !t.getUin().equals("")) {
				hql = hql + " and Uin = :uin";
			}
			if (null != t.getUserName() && !t.getUserName().equals("")) {
				hql = hql + " and UserName = :UserName";
			}
			if (null != t.getNickName() && !t.getNickName().equals("")) {
				hql = hql + " and NickName = :NickName";
			}
		}
		Query q = session.createQuery(hql);

		if (null != t && !t.equals("")) {

			if (null != t.getUin() && !t.getUin().equals("")) {
				q.setString("uin", t.getUin());
			}
			if (null != t.getUserName() && !t.getUserName().equals("")) {
				q.setString("UserName", t.getUserName());
			}
			if (null != t.getNickName() && !t.getNickName().equals("")) {
				q.setString("NickName", t.getNickName());
			}

		}
		List<User> list = q.list();
	
		session.close();
		
		
		return list;
	}

	@Override
	public void insert(User t) {
		Session session = (Session) sessionFactory.openSession();
		session.save(t);
		session.close();
	}

	@Override
	public void update(User t) {
		Session session = (Session) sessionFactory.openSession();
		session.update(t);
		session.close();
	}

	@Override
	public void delete(User t) {

		Session session = null;
		Transaction tx = null;

		session = sessionFactory.openSession();
		tx = session.beginTransaction();

		String hql = "delete from User  where  1=1 ";
		if (null != t && !t.equals("")) {
			if (null != t.getUin() && !t.getUin().equals("")) {
				hql = hql + " and Uin = :uin";
			}
			if (null != t.getUserName() && !t.getUserName().equals("")) {
				hql = hql + " and UserName = :UserName";
			}
			if (null != t.getNickName() && !t.getNickName().equals("")) {
				hql = hql + " and NickName = :NickName";
			}
		}
		Query q = session.createQuery(hql);

		if (null != t && !t.equals("")) {

			if (null != t.getUin() && !t.getUin().equals("")) {
				q.setString("uin", t.getUin());
			}
			if (null != t.getUserName() && !t.getUserName().equals("")) {
				q.setString("UserName", t.getUserName());
			}
			if (null != t.getNickName() && !t.getNickName().equals("")) {
				q.setString("NickName", t.getNickName());
			}

		}
		q.executeUpdate();
		tx.commit();
		session.close();

	}

}
